package com.ecspace.knowledgegraphapi.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ecspace.knowledgegraphapi.domain.dto.BusinessInfo;
import com.ecspace.knowledgegraphapi.domain.dto.NodeRelationDTO;
import com.ecspace.knowledgegraphapi.domain.entity.Relation;
import com.ecspace.knowledgegraphapi.domain.vo.RelationVO;
import com.ecspace.knowledgegraphapi.mapper.RelationMapper;
import com.ecspace.knowledgegraphapi.service.IRelationService;
import com.ecspace.knowledgegraphapi.util.StrUtil;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class RelationServiceImpl extends ServiceImpl<RelationMapper, Relation> implements IRelationService {

    @Override
    public List<RelationVO> listAll() {
        QueryWrapper<Relation> wrapper = new QueryWrapper<>();
        wrapper.select("DISTINCT name");
        List<Relation> list = list(wrapper);

        return list.stream()
        .map(relation -> new RelationVO(null, relation.getName(), null, null))
        .collect(Collectors.toList());
    }

    @Override
    public BusinessInfo saveNodeRelation(NodeRelationDTO relationDTO) {
        String fromId = relationDTO.getFromId();
        String toId = relationDTO.getToId();

        LambdaQueryWrapper<Relation> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Relation::getFromId, fromId).eq(Relation::getToId, toId);
        List<Relation> list = list(wrapper);
        if (list != null && list.size() > 0) {
            return BusinessInfo.getFailInfo("该源节点和目标节点已配置关系!");
        }

        String id = StrUtil.getUUIDStr();
        Relation relation = new Relation();
        relation.setId(id);
        relation.setName(relationDTO.getName());
        relation.setFromId(relationDTO.getFromId());
        relation.setToId(relationDTO.getToId());
        boolean ok = save(relation);
        return BusinessInfo.getSuccessInfo("节点关系配置成功");
    }


}
